import React, { useState, useEffect } from 'react';
import { Spin, Pagination } from 'antd';
import { 
  BankOutlined, 
  EnvironmentOutlined, 
  PhoneOutlined, 
  MailOutlined 
} from '@ant-design/icons';
import { useSearchParams } from 'react-router-dom';
import ProductCard from '../components/ProductCard';
import { ApiService } from '../services/api';
import './ProductsPage.css';

const ProductsPage = () => {
  const [searchParams] = useSearchParams();
  const [categories, setCategories] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [productsLoading, setProductsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [isHotProducts, setIsHotProducts] = useState(false);
  const [isCategoryMenuOpen, setIsCategoryMenuOpen] = useState(false);
  const [companyInfo, setCompanyInfo] = useState({
    companyName: '',
    address: '',
    mobile: '',
    email: ''
  });
  const pageSize = 10;

  // 获取产品分类
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const response = await ApiService.getMainCategoryList();
        
        if (response.code === '0000' && response.data) {
          setCategories(response.data);
        } else {
          setError('获取产品分类失败');
        }
      } catch (err) {
        console.error('获取产品分类失败:', err);
        setError('网络请求失败');
      } finally {
        setLoading(false);
      }
    };

    fetchCategories();
  }, []);

  // 获取公司信息
  useEffect(() => {
    const fetchCompanyInfo = async () => {
      try {
        const response = await ApiService.getCompanyDetail();
        
        if (response.code === '0000' && response.data) {
          setCompanyInfo({
            companyName: response.data[0].companyName || '',
            address: response.data[0].address || '',
            mobile: response.data[0].mobile || '',
            email: response.data[0].email || ''
          });
        }
      } catch (err) {
        console.error('获取公司信息失败:', err);
        // 使用默认值，不显示错误
      }
    };

    fetchCompanyInfo();
  }, []);

  // 获取产品列表
  const fetchProducts = async (categoryId, pageIndex = 1) => {
    try {
      setProductsLoading(true);
      
      const response = await ApiService.getCategoryProductListPage(categoryId, pageIndex, pageSize);
      
      if (response.code === '0000' && response.data) {
        // 转换API数据格式为ProductCard组件需要的格式
        const formattedProducts = response.data.map(item => ({
          id: item.productId,
          title: item.productName,
          description: '', // API没有返回描述，可以后续扩展
          image: item.picUrl || '📦', // 如果没有图片URL，使用默认图标
          category: selectedCategory ? categories.find(cat => cat.categoryId === selectedCategory)?.categoryName : '全部'
        }));
        
        setProducts(formattedProducts);
        setTotal(response.total || 0);
        setCurrentPage(pageIndex);
      } else {
        setError('获取产品列表失败');
      }
    } catch (err) {
      console.error('获取产品列表失败:', err);
      setError('网络请求失败');
    } finally {
      setProductsLoading(false);
    }
  };

  // 处理URL参数，设置初始筛选状态
  useEffect(() => {
    if (categories.length > 0) {
      const filter = searchParams.get('filter');
      const categoryId = searchParams.get('categoryId');
      
      if (filter === 'hot') {
        // 显示热门产品
        setIsHotProducts(true);
        setSelectedCategory(null);
        setCurrentPage(1);
        // 直接调用热门产品API
        const fetchHotProducts = async () => {
          try {
            setProductsLoading(true);
            setError(null);
            
            const response = await ApiService.getHotProductList();
            
            if (response.code === '0000' && response.data) {
              const formattedProducts = response.data.map(item => ({
                id: item.productId,
                title: item.productName,
                description: '',
                image: item.picUrl || '📦',
                category: '热门产品'
              }));
              
              setProducts(formattedProducts);
              setTotal(formattedProducts.length);
            } else {
              setError('获取热门产品失败');
            }
          } catch (err) {
            console.error('获取热门产品失败:', err);
            setError('网络请求失败');
          } finally {
            setProductsLoading(false);
          }
        };
        
        fetchHotProducts();
      } else if (filter === 'category' && categoryId) {
        // 显示指定分类的产品
        const categoryIdNum = categoryId;
        setIsHotProducts(false);
        setSelectedCategory(categoryIdNum);
        setCurrentPage(1);
        // 直接调用分类产品API
        fetchProducts(categoryIdNum, 1);
      } else {
        // 默认显示全部产品
        setIsHotProducts(false);
        setSelectedCategory(null);
        setCurrentPage(1);
        // 直接调用全部产品API
        fetchProducts(null, 1);
      }
    }
  }, [categories, searchParams]);

  // 处理分页变化（仅在用户手动操作时触发）
  useEffect(() => {
    // 只有在没有URL参数的情况下才自动触发初始加载
    const filter = searchParams.get('filter');
    const categoryId = searchParams.get('categoryId');
    
    if (categories.length > 0 && !isHotProducts && !filter && !categoryId) {
      fetchProducts(selectedCategory, 1);
    }
  }, [categories, searchParams]);

  // 处理分类选择
  const handleCategorySelect = (categoryId) => {
    setSelectedCategory(categoryId);
    setIsHotProducts(false);
    setCurrentPage(1); // 重置到第一页
    setIsCategoryMenuOpen(false); // 关闭移动端菜单
    // 直接调用分类产品API
    fetchProducts(categoryId, 1);
  };

  // 显示所有产品
  const handleShowAll = () => {
    setSelectedCategory(null);
    setIsHotProducts(false);
    setCurrentPage(1); // 重置到第一页
    setIsCategoryMenuOpen(false); // 关闭移动端菜单
    // 直接调用全部产品API
    fetchProducts(null, 1);
  };

  // 显示热门产品
  const handleShowHotProducts = async () => {
    try {
      setProductsLoading(true);
      setError(null);
      setIsHotProducts(true);
      setSelectedCategory(null);
      setIsCategoryMenuOpen(false); // 关闭移动端菜单
      
      const response = await ApiService.getHotProductList();
      
      if (response.code === '0000' && response.data) {
        // 转换API数据格式为ProductCard组件需要的格式
        const formattedProducts = response.data.map(item => ({
          id: item.productId,
          title: item.productName,
          description: '',
          image: item.picUrl || '📦',
          category: '热门产品'
        }));
        
        setProducts(formattedProducts);
        setTotal(formattedProducts.length);
        setCurrentPage(1);
      } else {
        setError('获取热门产品失败');
      }
    } catch (err) {
      console.error('获取热门产品失败:', err);
      setError('网络请求失败');
    } finally {
      setProductsLoading(false);
    }
  };

  // 处理分页变化
  const handlePageChange = (page) => {
    if (isHotProducts) {
      // 热门产品不分页，直接跳转
      return;
    }
    fetchProducts(selectedCategory, page);
  };

  // 切换分类菜单显示状态
  const toggleCategoryMenu = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsCategoryMenuOpen(!isCategoryMenuOpen);
  };

  // 点击外部区域关闭菜单
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (isCategoryMenuOpen && !event.target.closest('.category-sidebar')) {
        setIsCategoryMenuOpen(false);
      }
    };

    if (isCategoryMenuOpen) {
      document.addEventListener('click', handleClickOutside);
    }

    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [isCategoryMenuOpen]);

  if (loading) {
    return (
      <div className="products-page">
        <div className="container">
          <div className="page-header">
            <h1>产品中心</h1>
            <p>Product Center</p>
          </div>
          <div className="loading-container">
            <Spin size="large" />
            <p>加载产品分类中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="products-page">
        <div className="container">
          <div className="page-header">
            <h1>产品中心</h1>
            <p>Product Center</p>
          </div>
          <div className="error-container">
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="products-page">
      <div className="page-header">
        <h1>产品中心</h1>
        <p>Product Center</p>
      </div>

      <div className="products-layout">
        {/* 左侧分类侧边栏 */}
        <div className="category-sidebar">
          <div className="sidebar-header">
            <div className="sidebar-title">产品分类</div>
            <button className="category-menu-toggle" onClick={toggleCategoryMenu}>
              <span></span>
              <span></span>
              <span></span>
            </button>
          </div>
          <div className={`category-list ${isCategoryMenuOpen ? 'category-menu-open' : ''}`}>
            <div 
              className={`category-item ${!selectedCategory && !isHotProducts ? 'active' : ''}`}
              onClick={handleShowAll}
            >
              全部产品
            </div>
            <div 
              className={`category-item ${isHotProducts ? 'active' : ''}`}
              onClick={handleShowHotProducts}
            >
              热门产品
            </div>
            {categories.map(category => (
              <div 
                key={category.categoryId} 
                className={`category-item ${selectedCategory === category.categoryId ? 'active' : ''}`}
                onClick={() => handleCategorySelect(category.categoryId)}
              >
                {category.categoryName}
              </div>
            ))}
          </div>
          
          {/* 公司信息 */}
          <div className="company-info">
            <div className="company-details">
              <div className="company-item">
                <BankOutlined className="company-icon" />
                <span className="company-value">{companyInfo.companyName}</span>
              </div>
              <div className="company-item">
                <EnvironmentOutlined className="company-icon" />
                <span className="company-value">{companyInfo.address}</span>
              </div>
              <div className="company-item">
                <PhoneOutlined className="company-icon" />
                <span className="company-value">{companyInfo.mobile}</span>
              </div>
              <div className="company-item">
                <MailOutlined className="company-icon" />
                <span className="company-value">{companyInfo.email}</span>
              </div>
            </div>
          </div>
        </div>

        {/* 右侧产品展示区域 */}
        <div className="products-content">
          <div className="content-header">
            <h2>
              {isHotProducts ? '热门产品' : 
               selectedCategory ? categories.find(cat => cat.categoryId === selectedCategory)?.categoryName : '全部产品'}
            </h2>
            <p>共{total}个产品</p>
          </div>

          <div className="products-grid">
            {productsLoading ? (
              <div className="loading-container">
                <Spin size="large" />
                <p>加载产品中...</p>
              </div>
            ) : products.length > 0 ? (
              products.map(product => (
                <ProductCard key={product.id} product={product} />
              ))
            ) : (
              <div className="no-products">
                <p>暂无产品数据</p>
              </div>
            )}
          </div>

          {/* 分页组件 */}
          {total > 0 && !isHotProducts && (
            <div className="pagination-container">
              <Pagination
                current={currentPage}
                total={total}
                pageSize={pageSize}
                onChange={handlePageChange}
                showSizeChanger={false}
                showTotal={(total, range) => 
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                }
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ProductsPage;
